package com.bulletelc.apollopre.module.main.center.orders.refunk;

import com.bulletelc.apollopre.MyApplication;
import com.bulletelc.apollopre.constants.GlobalConfig;
import com.bulletelc.apollopre.constants.NetWorkPath;
import com.bulletelc.apollopre.framework.BasePresenter;
import com.bulletelc.apollopre.utils.LogUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by CX on 2018/1/28.
 */

public class RefunkPresenter extends BasePresenter<RefunkContract.View> implements RefunkContract.Present {
    @Override
    public void refunkApply(String json) {
        commitApply(json);
    }

    @Override
    public void start() {

    }

    @Override
    public void stop() {

    }

    private void commitApply(String json) {
        RequestBody body = RequestBody.create(MediaType.parse(GlobalConfig.CONTENT_TYPE_JSON), json);
        OkGo.<String>post(NetWorkPath.POST_SERVICE_ORDER_APPLY)
                .headers(NetWorkPath.HEADER_KEY_AUTH, GlobalConfig.AUTH_HEAD + MyApplication.getToken())
                .upRequestBody(body)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseCommitApply(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (isViewAttached()) {
                            getView().onErrorApply(response.getException().toString());
                        }
                    }
                });
    }

    private void parseCommitApply(Response<String> response) {
        if (response.isSuccessful()) {
            try {
                JSONObject obj = new JSONObject(response.body().toString());
                JSONObject objMeta = new JSONObject(obj.getString("meta"));
                if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(objMeta.getString("code"))) {
                    if (isViewAttached()) {
                        getView().onSuccessApply();
                    }
                } else {
                    if (isViewAttached()) {
                        getView().onFailApply(objMeta.getString("msg"));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                if (isViewAttached()) {
                    getView().onErrorApply("数据解析错误");
                }
            }
        } else {
            if (isViewAttached()) {
                getView().onFailApply(response.body().toString());
            }
        }
    }
}
